package com.chhuang.ewcrm.thread;

import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.comm.CommInfraRedValue;
import com.chhuang.ewcrm.comm.CommStartListener;
import com.chhuang.ewcrm.comm.Serial;
import com.chhuang.ewcrm.dao.WWeighCtrlerDao;
import com.chhuang.ewcrm.entity.WWeighCtrler;
import com.chhuang.ewcrm.utils.MyAlert;
import com.jfoenix.controls.JFXButton;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.UnsupportedCommOperationException;
import javafx.scene.control.Label;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.TooManyListenersException;

import static javafx.application.Platform.runLater;

/**
 * 过磅控制设备串口通讯线程
 * @author chhuang
 * @create 2020-10-12-14:36
 */
public class InitCtrlCommThread implements Runnable {
    private final Logger logger = LoggerFactory.getLogger(InitCtrlCommThread.class);

    private CommStartListener lightCommStartListener;//监听红绿灯和红外状态

    private final JFXButton greenButton1;
    private final JFXButton redButton1;
    private final JFXButton greenButton2;
    private final JFXButton redButton2;
    private final Label infraredLabel1;
    private final Label infraredLabel2;

    private InfraRedThread infraRedThread;

    private boolean enableTrafficLights = false;//是否开启了红绿灯功能

    private WWeighCtrlerDao wWeighCtrlerDao = App.getSession().getMapper(WWeighCtrlerDao.class);

    public InitCtrlCommThread(JFXButton greenButton1, JFXButton redButton1,
                              JFXButton greenButton2, JFXButton redButton2,
                              Label infraredLabel1, Label infraredLabel2){
        this.greenButton1 = greenButton1;
        this.redButton1 = redButton1;
        this.greenButton2 = greenButton2;
        this.redButton2 = redButton2;
        this.infraredLabel1 = infraredLabel1;
        this.infraredLabel2 = infraredLabel2;
    }

    @Override
    public void run() {
        try {
            initComm();
        } catch (PortInUseException | IOException | NoSuchPortException | TooManyListenersException | UnsupportedCommOperationException e) {
            runLater(() -> {
                infraredLabel1.setStyle(CommInfraRedValue.ORANGE_BACKGROUND);
                infraredLabel2.setStyle(CommInfraRedValue.ORANGE_BACKGROUND);
            });
            e.printStackTrace();
            MyAlert.showErrorLater("错误",null, "打开串口出错，请查看串口配置信息是否有误。");
        }
    }

    /**
     * 初始化串口
     */
    private void initComm() throws PortInUseException, IOException, NoSuchPortException, TooManyListenersException, UnsupportedCommOperationException {
        WWeighCtrler wWeighCtrler = wWeighCtrlerDao.queryById("001");
        if(wWeighCtrler==null) return;
        logger.debug("过磅系统控制器参数为："+wWeighCtrler.toString());

        enableTrafficLights = wWeighCtrler.getWctrlEnableTrafficLights();
        boolean enableInfrared = wWeighCtrler.getWctrlEnableInfrared();

        if(enableTrafficLights || enableInfrared){//获取配置信息判断 是否开启红绿灯或红外功能
            //获取配置信息，串口名称，波特率，数据位，停止位，效验位
            lightCommStartListener = new CommStartListener(
                    new Serial(wWeighCtrler.getWctrlComm(),
                            wWeighCtrler.getWctrlBaudrate(),
                            wWeighCtrler.getWctrlDatabits(),
                            wWeighCtrler.getWctrlStopbits(),
                            wWeighCtrler.getWctrlParity()),
                    new CommInfraRedValue(infraredLabel1, infraredLabel2));

            if(enableTrafficLights){//是否开启红绿灯
                runLater(()->{
                    greenButton1.setOnAction(event -> lightCommStartListener.send(CommInfraRedValue.LINGHT1_GREEN));//南绿灯亮发送
                    redButton1.setOnAction(event -> lightCommStartListener.send(CommInfraRedValue.LINGHT1_RED));//南红灯亮发送

                    greenButton2.setOnAction(event -> lightCommStartListener.send(CommInfraRedValue.LINGHT2_GREEN));//北绿灯亮发送
                    redButton2.setOnAction(event -> lightCommStartListener.send(CommInfraRedValue.LINGHT2_RED));//北红灯亮发送
                });
            }

            if(enableInfrared){//是否开启红外功能
                infraRedThread = new InfraRedThread(lightCommStartListener);
                new Thread(infraRedThread).start();//定时发送查询红外感应器状态
            }
        }
    }

    public void lingt1Green(){
        if(enableTrafficLights && lightCommStartListener!=null)//开启红绿灯功能 并且 监听正常启动
            lightCommStartListener.send(CommInfraRedValue.LINGHT1_GREEN);
    }
    public void lingt1Red(){
        if(enableTrafficLights && lightCommStartListener!=null)//开启红绿灯功能 并且 监听正常启动
            lightCommStartListener.send(CommInfraRedValue.LINGHT1_RED);
    }
    public void lingt2Green(){
        if(enableTrafficLights && lightCommStartListener!=null)//开启红绿灯功能 并且 监听正常启动
            lightCommStartListener.send(CommInfraRedValue.LINGHT2_GREEN);
    }
    public void lingt2Red(){
        if(enableTrafficLights && lightCommStartListener!=null)//开启红绿灯功能 并且 监听正常启动
            lightCommStartListener.send(CommInfraRedValue.LINGHT2_RED);
    }

    /**
     * 关闭串口连接
     */
    public void close(){
        if(lightCommStartListener!=null)
            lightCommStartListener.close();

        if(infraRedThread!=null)
            infraRedThread.close();
    }
}
